package com.api_getway.api_getway.config.handler;

import com.example.commons.utils.ApiResult;
import com.example.commons.utils.JinZhiException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * 全局覆盖处理
 */
@Order(-1)
@Configuration
public class GlobalErrorExceptionHandler  implements ErrorWebExceptionHandler {
    private final ObjectMapper objectMapper=new ObjectMapper();
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        if (response.isCommitted()) {
            return Mono.error(ex);
        }
        // 设置返回JSON
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //比如这里的异常是token过期异常  虽然他们俩个都是返回到登录页面，但是我怎么知道他们的异常信息到底是过期  还是未登录呢
        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            try {
                //返回响应结果
                ApiResult<String> result=new ApiResult<>();
                result.setMsg(ex.getMessage());
                Map map=new HashMap();
                //比如这里的异常是未登录异常
                if (ex instanceof JinZhiException) {
                    int code =((JinZhiException) ex).getCode();
                    if(code==28004||code==509){
                        map.put("code",28004);
                        map.put("data","验证失败");
                    }else {
                        map.put("code",500);
                        map.put("data","出现异常");
                    }
                }

                map.put("success",false);

                return bufferFactory.wrap(objectMapper.writeValueAsBytes(map));
            }
            catch (JsonProcessingException e) {
                return bufferFactory.wrap(new byte[0]);
            }
        }));

    }
}